package com.wuge.auth.controller;

import com.wuge.auth.feign.ThirdPartSmsFeign;
import com.wuge.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Controller
public class SmsController {
    @Autowired
   private StringRedisTemplate stringRedisTemplate;
    @Resource
    private ThirdPartSmsFeign  thirdPartSmsFeign;
    @RequestMapping("/sms/sendCode")
    @ResponseBody
    public R sms(@RequestParam("phone") String phone){
        if (StringUtils.isEmpty(phone)){
            return R.error(10001,"手机号格式有误");
        }
        String store_code = stringRedisTemplate.opsForValue().get("phone_code" + phone);
        if (!StringUtils.isEmpty(store_code)){
            String[] s = store_code.split("_");
            if (System.currentTimeMillis()-Long.parseLong(s[1])<60000){
                return R.error(10001,"验证码发送频繁,请稍后重试");
            }

        }
//        生成验证码
         String code=String.valueOf((int)((Math.random()*8+1)*100000));
        thirdPartSmsFeign.sendCode(phone,code);
        System.out.println("验证码为:"+code);
        String redis_code=code+"_"+System.currentTimeMillis();
        stringRedisTemplate.opsForValue().set("phone_code" + phone,redis_code,10, TimeUnit.MINUTES);
        return R.ok();
    }
}
